package lily.phs.epidemic;


import java.util.ArrayList;
import java.util.Calendar;
import lily.phs.object.EpidemicRecord;
import lily.phs.child.ImageList;
import lily.phs.database.Constants;
import lily.phs.urh.R;
import lily.ui.bookshelf.CaseLevelView;
import lily.ui.bookshelf.ProfileView;
import lily.ui.bookshelf.WindowSizeUtil;
import lily.ui.control.MyPopupWindow;
import lily.ui.control.SearchPopupWindow;
import lily.ui.panel.Panel;
import lily.ui.panel.Panel.OnPanelListener;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class EpidemicList extends Activity implements OnClickListener,OnFocusChangeListener,Constants,OnPanelListener,
	OnItemClickListener{

	private static final String[] PROJECTION = new String[]{_ID, 
		INDI_ID/*卡片ID*/, 
		INDI_NAME};
	private int userid;
	private View view;
	private ArrayList<CaseLevelView> AllLevels;
	private LinearLayout ll_Content;
	private int ProfilesSUM;//卡片总数
	private int ProfilesInOneLevel;//每层最多可放置的卡片数
	private String[] allProfiles;
	AlertDialog ad;
	MyPopupWindow mPopupWindow;
	Button leftBtn;
    Button rightBtn ;
    Button rightBtn2;
    private int idList[];
    private ProgressDialog mpDialog;
    private SearchPopupWindow sPopupWindow;
    GridView grid;
    
    EditText et_id,et_name,et_jdr,et_date;
    private TextView tvTitle;
	private Panel panel;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
        LayoutInflater factory = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = factory.inflate(R.layout.profilecase, null);
        tvTitle = (TextView)view.findViewById(R.id.title);
        tvTitle.setText("传染病疫情上报管理");
        
        panel = (Panel)view.findViewById(R.id.bottompanel);
        
        ll_Content = (LinearLayout)view.findViewById(R.id.shelves_content);
        AllLevels = new ArrayList<CaseLevelView>();
        
        addNewLevel();
        addNewLevel();
        addNewLevel();
        addNewLevel();
        addNewLevel();
        addNewLevel();//初始时加入6层以填充界面
        
//        //初始化卡片架
//		initContentView();
        mpDialog = new ProgressDialog(EpidemicList.this);  
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
		mpDialog.setMessage("正在加载...");  
		mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
		mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
		mpDialog.show();
		new myThread(handler,"",2).start();
		
		leftBtn = (Button) findViewById(R.id.title_left_btn);
        rightBtn = (Button) findViewById(R.id.title_right_btn);
        rightBtn2 = (Button) findViewById(R.id.title_right_btn2);
        leftBtn.setText("后退");
        rightBtn.setVisibility(View.INVISIBLE);
        rightBtn2.setVisibility(View.INVISIBLE);
        leftBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
			}
        	
        });
		grid = (GridView)this.findViewById(R.id.bottomgrid);
		String[] menus = new String[]{"新建","查询","刷新"};
		int[] images = new int[]{R.drawable.add_files,R.drawable.search_file,R.drawable.fresh};
		ImageList adapter = new ImageList(this,images,menus);
		grid.setAdapter(adapter);
		grid.setOnItemClickListener(this);
		
	}
	

	
	/******************************************************************/
    private int getProfilesInOneLevel() {
    	// TODO Auto-generated method stub
		//每一层可放的卡片数
    	WindowSizeUtil util = new WindowSizeUtil(this);
		ProfileView newProfile = new ProfileView(this);
		return util.ScreenWidth/newProfile.FileWidth;
		
    }
    
    /**
	 * 添加一个新的健康卡片
	 * @param level 放置的层
	 * @param ProfileName 卡片名
	 * @param ProfileId 卡片ID
	 */
	private void addNewProfileInLevel(int level,String ProfileName,int ProfileId) {
		// TODO Auto-generated method stub
		ProfileView newProfile = new ProfileView(this);
		String s=""+ProfileId;
		newProfile.button.setText(ProfileName);//卡片名称
		newProfile.button.setId(ProfileId);//卡片编号
		newProfile.button.setContentDescription(s);
		System.out.println("addFile=========="+ProfileName+"  "+ProfileId);
		newProfile.button.setOnClickListener(this);
		
		if(level>=AllLevels.size()){
			addNewLevel();
		}
		AllLevels.get(level).addView(
				newProfile,//,newProfile.FileWidth,newProfile.FileHeight);
				MeasureSpec.makeMeasureSpec(newProfile.FileWidth, MeasureSpec.EXACTLY),
				MeasureSpec.makeMeasureSpec(newProfile.FileHeight, MeasureSpec.EXACTLY));

		System.out.println("addFile:"+newProfile.FileWidth+","+newProfile.FileHeight);
		setContentView(view);
	}
	
	/**
	 * 添加一个新的层
	 */
	private void addNewLevel() {
		// TODO Auto-generated method stub
		CaseLevelView newcaseLevelView = new CaseLevelView(this);
		AllLevels.add(newcaseLevelView);
		ll_Content.addView(
				newcaseLevelView,newcaseLevelView.LevelWidth,newcaseLevelView.LevelHeight);//
		System.out.println("addLevel:"+newcaseLevelView.LevelWidth+","+newcaseLevelView.LevelHeight);
		setContentView(view);
	}
	
	/**
	 * 初始化整个界面
	 */
	protected void initContentView() {
		System.out.println("11111111______");
		// TODO Auto-generated method stub		
		for(int i=0;i<AllLevels.size();i++){
			AllLevels.get(i).removeAllViews();
		}
		Cursor cursor = this.managedQuery(CONTENT_URI_TB20, PROJECTION , null/*USPE_ID+"='"+userid+"'"*/, null, null);
		ProfilesSUM = cursor.getCount();
		System.out.println("ProfilesSUM="+ProfilesSUM);
		ProfilesInOneLevel = getProfilesInOneLevel();//计算每层可以存放的卡片数
        System.out.println("ProfilesInOneLevel="+ProfilesInOneLevel);
        
		allProfiles = new String[ProfilesSUM];
		
		for(int i=0;i<allProfiles.length;i++){
        	cursor.moveToNext();
        	allProfiles[i] = cursor.getString(cursor.getColumnIndex(INDI_NAME));
        	
        	int ID = cursor.getInt(cursor.getColumnIndex(INDI_ID));
            int selectedLevel = i / ProfilesInOneLevel;//新卡片应放置的层
            System.out.println("selectedLevel="+selectedLevel);
            System.out.println("INDI_ID========"+cursor.getInt(cursor.getColumnIndex(INDI_ID)));
    		System.out.println("INDI_NAME========"+cursor.getString(cursor.getColumnIndex(INDI_NAME)));
        }
		
	}
	
	private boolean ProfileExist(String name) {
		// TODO Auto-generated method stub
		for(int i=0;i<allProfiles.length;i++){
			if(allProfiles[i].equals(name))
				return true;
		}
		return false;
	}
	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int i=v.getId();
		System.out.println(i);
		Intent editprofile = new Intent();
		Bundle bd = new Bundle();
		bd.putInt("Profile_id", i);
//		bd.putInt("father", MODULE_FATHER);
//		bd.putInt("call", MODULE_LIST);
		editprofile.putExtras(bd);
		editprofile.setClass(EpidemicList.this, Epidemic.class);
		startActivity(editprofile);
		overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
		
	}

	@Override
	public void onPanelClosed(Panel panel) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPanelOpened(Panel panel) {
		// TODO Auto-generated method stub
		
	}
	
	public class myThread extends Thread{  
		private Handler handler;
		private String str;
		private int state;
		public myThread(Handler handler,String s,int state){
			this.handler=handler;
			this.str=s;
			this.state=state;
		}
		
		public void run(){  
	        try  
	        {   
	        	Looper.getMainLooper();
	        	sleep(200); 
	        	Message msg = handler.obtainMessage(); 
	        	searchContentView(this.str,this.state);
        		msg.what=1;
	        	handler.sendMessage(msg); 
			}  
		    catch (Exception e)  
		    {  
		        e.printStackTrace();  
		    }  
		}  
	}
	
	private final Handler handler = new Handler(Looper.getMainLooper()) {
    	public void handleMessage(Message msg) { // 处理Message，更新ListView 
    		if(msg.what==1){
    			for(int i=0;i<AllLevels.size();i++){
    				AllLevels.get(i).removeAllViews();
    			}
    			ProfilesInOneLevel = getProfilesInOneLevel();
    			if(ProfilesInOneLevel<1){
    				ProfilesInOneLevel=4;
    			}
    			for(int i=0;i<allProfiles.length;i++){
    	            int selectedLevel = i / ProfilesInOneLevel;//新卡片应放置的层
    	            System.out.println("selectedLevel="+selectedLevel);
    	            addNewProfileInLevel(selectedLevel,allProfiles[i],idList[i]);
    	        }
    			mpDialog.cancel();
    		}
    		
    	} 
    }; 
    
    protected void searchContentView(String name,int state) {
		// TODO Auto-generated method stub
		//取出该用户的全部卡片
		Cursor cursor;
		name=name.replace(" ", "");
		if(state==1){
		cursor= this.managedQuery(CONTENT_URI_TB20,PROJECTION, 
				INDI_NAME+" LIKE '%"+name+"%'", null, null);
		}
		else {
			cursor = this.managedQuery(CONTENT_URI_TB20, PROJECTION , null, null, null);
		}
		ProfilesSUM = cursor.getCount();        
		allProfiles = new String[ProfilesSUM];
        idList=new int[ProfilesSUM];
        for(int i=0;i<allProfiles.length;i++){
        	cursor.moveToNext();
        	idList[i]=cursor.getInt(cursor.getColumnIndex(INDI_ID));
        	allProfiles[i] =cursor.getString(cursor.getColumnIndex(INDI_NAME));
        	System.out.println("allProfiles[i]="+allProfiles[i]+" ,idList[i]="+idList[i]);
        }
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		if(arg0==grid){
			panel.setOpen(false, false);
			
			switch (arg2) {
			case 0:
				LayoutInflater factory = LayoutInflater.from(getBaseContext());
	            final View textEntryView = factory.inflate(R.layout.build_new_epidemic, null);
	            et_date=(EditText)textEntryView.findViewById(R.id.et_new_date);
	            et_date.setInputType(InputType.TYPE_NULL);
	            et_date.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mPopupWindow = new MyPopupWindow(getBaseContext());			
						mPopupWindow.showAtLocation(textEntryView.findViewById(R.id.et_new_date), Gravity.CENTER, 0, 0);

						Button btn=mPopupWindow.getButton();
						btn.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								et_date.setText(mPopupWindow.getDate());
								mPopupWindow.dismiss();
							}
							
						});
					}
	            	
	            });
	            et_date.setOnFocusChangeListener(new OnFocusChangeListener() {
					
					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						// TODO Auto-generated method stub
						if(v==et_date&&hasFocus){
							mPopupWindow = new MyPopupWindow(getBaseContext());			
							mPopupWindow.showAtLocation(textEntryView.findViewById(R.id.et_new_date), Gravity.CENTER, 0, 0);

							Button btn=mPopupWindow.getButton();
							btn.setOnClickListener(new OnClickListener(){

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									et_date.setText(mPopupWindow.getDate());
									mPopupWindow.dismiss();
								}
								
							});
						}
					}
				});
	            ad=new AlertDialog.Builder(EpidemicList.this)
	                .setIcon(R.drawable.add_profile)
	                .setTitle("新建传染病报告卡")
	                .setView(textEntryView).create();
	            ad.show();
	               
	            
	            Button bt_ok=(Button)textEntryView.findViewById(R.id.bt_new_ok);
	            Button bt_cancle=(Button)textEntryView.findViewById(R.id.bt_new_cancle);
	            bt_ok.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
//							et_id=(EditText)textEntryView.findViewById(R.id.et_new_id);
				            et_name=(EditText)textEntryView.findViewById(R.id.et_new_name); 
				            et_jdr=(EditText)textEntryView.findViewById(R.id.et_new_reporter);
				            
				            
							if(et_name.getText().toString().length()<1){
								et_name.setError("姓名不能为空!");
							}
							else if(et_date.getText().toString().length()<1){
								et_date.setError("填卡日期不能为空!");
							}
							else{
								mpDialog = new ProgressDialog(EpidemicList.this);  
								mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
								mpDialog.setMessage("正在新建报告卡...");  
								mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
								mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
								mpDialog.show();
								createProfiles();  
								new myThread(handler,"",2).start();
								ad.cancel();
							}
							
						}
	                	
	                });
	                
	                bt_cancle.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							ad.cancel();
						}
	                	
	                });
	                break;
			case 1:
				sPopupWindow = new SearchPopupWindow(getBaseContext());		
				sPopupWindow.showAtLocation(findViewById(R.id.title_left_btn), Gravity.CENTER, 0, 0);
				sPopupWindow.setAnimationStyle(R.anim.i_slide_in_left);
				final Button bt=sPopupWindow.getBt();
				final EditText et=sPopupWindow.getEt();
				bt.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						//searchContentView(et.getText().toString());
						mpDialog = new ProgressDialog(EpidemicList.this);  
						mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
						mpDialog.setMessage("正在搜索...");  
						mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
						mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
						mpDialog.show();
						new myThread(handler,et.getText().toString(),1).start();
					}
					
				});
				break;
			case 2:
				mpDialog = new ProgressDialog(EpidemicList.this);  
				mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
				mpDialog.setMessage("正在刷新...");  
				mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
				mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
				mpDialog.show();
				new myThread(handler,"",2).start();
				
			default:
				break;
			}
		}
	}
	
	public void createProfiles(){
		Calendar c=Calendar.getInstance();
		String s=c.getTimeInMillis()+"";
		System.out.println(s);
		int pro=Integer.parseInt(s.substring(4));
		System.out.println(pro);
	    EpidemicRecord ep=new EpidemicRecord(getBaseContext());
		ep.setIndi_id(pro);
		System.out.println(s);	
		ep.setIndi_name(et_name.getText().toString());
		ep.setIndi_report(et_jdr.getText().toString());
		ep.setIndi_fill_date(et_date.getText().toString());
		ep.setIndi_province("甘肃");
		ep.setIndi_city("兰州");
		ep.setIndi_country("永登");
//		ep.setIndi_village("巴家");
//		ep.setIndi_town("巴州");
		ep.insertEpidemicRecord();
		System.out.println(ep.getIndi_name());}



	@Override
	public void onFocusChange(View arg0, boolean arg1) {
		// TODO Auto-generated method stub
		
	}


}



